package com.cn.encryp;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 数字签名算法
 * @Author 朱明川
 * @Date 2023/7/20 11:22
 * @Version 1.0
 *
 * todo 1 简介
 * DSA (Digital Signature Algorithm) 是 Schnorr 和 ElGamal 签名算法的变种，被美国 NIST 作为 DSS (DigitalSignature Standard)。
 * DSA 是基于整数有限域离散对数难题的。
 * 简单的说，这是一种更高级的验证方式，用作数字签名。不单单只有公钥、私钥，还有数字签名。私钥加密生成数字签名，公钥验证数据及签名，如果数据和签名
 * 不匹配则认为验证失败。数字签名的作用就是校验数据在传输过程中不被修改，数字签名，是单向加密的升级。
 *
 * todo 2 处理过程
 * 1) 使用消息摘要算法将发送数据加密生成数字摘要。
 * (2) 发送方用自己的私钥对摘要再加密，形成数字签名。
 * (3) 将原文和加密的摘要同时传给对方。
 * (4) 接受方用发送方的公钥对摘要解密，同时对收到的数据用消息摘要算法产生同一摘要。
 * (5) 将解密后的摘要和收到的数据在接收方重新加密产生的摘要相互对比，如果两者一致，则说明在传送过程中信息没有破坏和篡改。否则，则说明信息已经失去安全性和保密性。
 *
 */

public class DSA {


    /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * 签名算法
     */
    public static final String SIGNATURE_ALGORITHM = "SHA256withRSA";


    /**
     * 获取公钥的key
     */
    private static final String PUBLIC_KEY_STR = "PublicKeyStr";

    /**
     * 获取私钥的key
     */
    private static final String PRIVATE_KEY_STR = "PrivateKeyStr";


    /**
     * RSA最大加密明文大小(字节数)
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小(字节数)
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * @description: 生成公钥私钥
     * @date: 2024/1/17 14:47
     * @param
     * @return java.util.Map<java.lang.String,java.lang.String>
     */
    public static Map<String, String> initKeyPair() throws Exception {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        kpg.initialize(1024);
        KeyPair keyPair = kpg.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        String publicKeyStr = encryptBASE64(publicKey.getEncoded());
        String privateKeyStr = encryptBASE64(privateKey.getEncoded());

        Map<String, String> keyMap = new HashMap<>();
        keyMap.put(PUBLIC_KEY_STR, publicKeyStr);
        keyMap.put(PRIVATE_KEY_STR, privateKeyStr);
        return keyMap;
    }

    /**
     * @description:  私钥加密
     * @param str 待加密字符串
     * @param key 私钥
     * @return java.lang.String
     */
    public static String encryptByPrivateKey(String str, String key) throws Exception {
        byte[] data = str.getBytes();
        PrivateKey privateKey = strToPrivateKey(key);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        byte[] bytes = dataSegment(data, cipher, MAX_ENCRYPT_BLOCK);
        return encryptBASE64(bytes);
    }


    /**
     * @description:  公钥解密
     * @param str 待解密字符串
     * @param key 公钥
     * @return java.lang.String
     */
    public static String decryptByPublicKey(String str, String key) throws Exception {
        byte[] data = decryptBASE64(str);
        PublicKey publicKey = strToPublicKey(key);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        byte[] bytes = dataSegment(data, cipher, MAX_DECRYPT_BLOCK);
        return new String(bytes);
    }


    /**
     * @description:  使用私钥对数据进行数字签名
     * @param str 待加签字符串
     * @param privateKey 私钥
     * @return java.lang.String
     */
    public static String sign(String str, String privateKey) throws Exception {
        byte[] data = str.getBytes();
        PrivateKey priKey = strToPrivateKey(privateKey);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(priKey);
        signature.update(data);
        byte[] bytes = signature.sign();
        return encryptBASE64(bytes);
    }


    /**
     * @description: 使用公钥对数据验证签名
     * @param str 待验签字符串(即要加签的内容)
     * @param publicKey 公钥
     * @param sign 数据签名
     * @return boolean
     */
    public static boolean verify(String str, String publicKey, String sign) throws Exception {
        byte[] data = str.getBytes();
        byte[] signBytes = decryptBASE64(sign);
        PublicKey pubKey = strToPublicKey(publicKey);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(pubKey);
        signature.update(data);
        return signature.verify(signBytes);
    }

    /**
     * @description: 对数据进行分段加密或解密
     * @param data
     * @param cipher
     * @param maxBlock
     * @return byte[]
     */
    private static byte[] dataSegment(byte[] data, Cipher cipher, int maxBlock) throws Exception{
        byte[] toByteArray;
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        int i = 0;
        byte[] cache;
        // 对数据分段加密解密
        while (inputLen - offSet > 0) {
            int var = inputLen - offSet > maxBlock ? maxBlock : inputLen - offSet;
            cache = cipher.doFinal(data, offSet, var);
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * maxBlock;
        }
        toByteArray = out.toByteArray();
        out.close();
        return toByteArray;
    }


    /**
     * @description: 获取私钥
     * @param str 私钥字符串
     * @return java.security.PrivateKey
     */
    private static PrivateKey strToPrivateKey(String str) throws Exception {
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(decryptBASE64(str));
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        return privateKey;
    }

    /**
     * @description: 获取公钥
     * @param str 公钥字符串
     * @return java.security.PrivateKey
     */
    private static PublicKey strToPublicKey(String str) throws Exception {
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(decryptBASE64(str));
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
        return publicKey;
    }


    /**
     * @description:  字节数组转字符串
     * @param bytes 字节数组
     * @return java.lang.String
     */
    private static String encryptBASE64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }


    /**
     * @description: 字符串转字节数组
     * @param str 字符串
     * @return byte[]
     */
    private static byte[] decryptBASE64(String str) {
        return Base64.getDecoder().decode(str);
    }

    public static void main(String[] args) throws Exception {
        // 获取公钥私钥
        Map<String, String> keyMap = initKeyPair();
        String publicKey = keyMap.get(PUBLIC_KEY_STR);
        String privateKey = keyMap.get(PRIVATE_KEY_STR);
        System.out.println("公钥: " + publicKey);
        System.out.println("私钥: " + privateKey);

        String data = "123456";
        System.out.println("源数据: " + data);

        // 私钥加密公钥解密
        String encryptData2 = encryptByPrivateKey(data, privateKey);
        String decryptData2 = decryptByPublicKey(encryptData2, publicKey);
        System.out.println("私钥加密结果: " + encryptData2);
        System.out.println("公钥解密结果: " + decryptData2);
        System.out.println();

        // 私钥加签公钥验签
        String data2 = "abc123369";
        String sign = sign(data2, privateKey);
        boolean flag = verify(data2, publicKey, sign);
        System.out.println("私钥加签结果: " + sign);
        System.out.println("公钥验签结果: " + flag);
    }
}
